
#include "Connection.h"

Connection::Connection(EventLoop *loop, Socket *clientsock)
    : loop_(loop), clientsock_(clientsock)
{
    clientchannel_ = new Channel(loop_, clientsock->fd());
    clientchannel_->setreadcallback(std::bind(&Connection::onmessage, this));
    clientchannel_->setclosecallback(std::bind(&Connection::closecallback,this));
    clientchannel_->seterrorcallback(std::bind(&Connection::errorcallback,this));
    clientchannel_->enablereading();
    clientchannel_->useet();

    // printf(" hahaNew client connected: %s:%d\n", clientsock_->ip().c_str(), clientsock_->port());
}
Connection::~Connection()
{
    delete clientsock_;
    delete clientchannel_;
}
std::string Connection::ip()
{
    return clientsock_->ip();
}
uint16_t Connection::port()
{
    return clientsock_->port();
}

int Connection::fd() const
{
    return clientsock_->fd();
}

void Connection::closecallback()
{
    // printf("client(eventfd=%d) disconnected.\n", fd());
    // close(fd());
    closecallback_(this);
}
void Connection::errorcallback()
{
    // printf("else error\n");
    // close(fd());
    errorcallback_(this);
}

void Connection::setclosecallback(std::function<void(Connection*)> f)
{
    closecallback_ = f;
}
void Connection::seterrorcallback(std::function<void(Connection*)> f)
{
    errorcallback_ = f;
}

void Connection::onmessage()
{
    char buffer[1024];

    while (true)
    {                                   // 非阻塞IO循环读取
        bzero(&buffer, sizeof(buffer)); // 清空缓冲区

        ssize_t nread = read(fd(), buffer, sizeof(buffer));

        if (nread > 0)
        { // 成功读取数据
            printf("recv(eventfd=%d):%s\n", fd(), buffer);
            inputbuffer_.append(buffer,nread);

            // for (size_t i = 0; i < (size_t)nread; i++)
            // {
            //     buffer[i] = toupper(buffer[i]);
            // }

            // send(fd(), buffer, nread, 0); // 原样回发（使用nread而非strlen）
        }
        else if (nread == -1 && errno == EINTR)
        { // 被信号中断
            continue;
        }
        else if (nread == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))
        { // 非阻塞无数据

            outputbuffer_ = inputbuffer_;
            // 暂时这样写
            write(fd(),outputbuffer_.data(),outputbuffer_.size());
            inputbuffer_.clear();

            break;
        }
        else if (nread == 0)
        { // 客户端断开连接
            // printf("client(eventfd=%d) disconnected.\n", fd_);
            // close(fd_);
            // closecallback_();
            closecallback();
            break;
        }
    }

}